import { BehaviorSubject } from 'rxjs';

declare global {
  interface Window {
    electron: {
      executeCommand: (command: string) => Promise<CommandResult>;
      getCurrentDirectory: () => string;
    };
  }
}

export interface CommandResult {
  output: string;
  error?: string;
  exitCode: number;
}

export interface ITerminalService {
  executeCommand(command: string): Promise<CommandResult>;
  getCommandHistory(): string[];
  getCurrentDirectory(): string;
  commandOutput$: BehaviorSubject<CommandResult | null>;
}

class TerminalService implements ITerminalService {
  private commandHistory: string[] = [];
  private currentDirectory: string = '/';
  public commandOutput$ = new BehaviorSubject<CommandResult | null>(null);

  constructor() {
    // Initialize current directory
    if (window.electron) {
      this.currentDirectory = window.electron.getCurrentDirectory();
    }
  }

  async executeCommand(command: string): Promise<CommandResult> {
    try {
      // Use Electron IPC if available, otherwise fall back to mock implementation
      if (window.electron) {
        const result = await window.electron.executeCommand(command);
        this.commandHistory.push(command);
        this.commandOutput$.next(result);
        return result;
      } else {
        // Mock implementation for development
        const result: CommandResult = {
          output: `Mock output for command: ${command}`,
          exitCode: 0
        };
        
        this.commandHistory.push(command);
        this.commandOutput$.next(result);
        return result;
      }
    } catch (error) {
      const errorResult: CommandResult = {
        output: '',
        error: error instanceof Error ? error.message : 'Unknown error',
        exitCode: 1
      };
      this.commandOutput$.next(errorResult);
      return errorResult;
    }
  }

  getCommandHistory(): string[] {
    return [...this.commandHistory];
  }

  getCurrentDirectory(): string {
    return this.currentDirectory;
  }
}

export const terminalService = new TerminalService(); 